<script lang="ts" setup>
import { onMounted, ref, nextTick } from "vue";
import VideoPlayer from "./components/VideoPlayer.vue";

const videoUrl = ref("");
const currentUrl = ref("");
const showPlayer = ref(false);
const loading = ref(false);
const errorMessage = ref("");
const historyList = ref([]);
const MAX_HISTORY = 10; // 最大保存历史记录数
const playerRef = ref(null)

// 视频检测逻辑
const testVideo = async () => {
  if (!videoUrl.value) return;

  loading.value = true;
  errorMessage.value = "";
  currentUrl.value = videoUrl.value;
  showPlayer.value = true;

  try {
    const valid = await verifyVideoLink(videoUrl.value);
    if (!valid) throw new Error("链接不可用");
    addHistory(videoUrl.value);
  } catch (err) {
    errorMessage.value = "无法播放：" + err.message;
    showPlayer.value = false;
  } finally {
    loading.value = false;
  }
};

// 简单链接验证（实际需要更完善的验证）
const verifyVideoLink = async (url) => {
  try {
    const response = await fetch(url, { method: "HEAD" });
    return response.ok;
  } catch {
    return false;
  }
};

// 新增历史记录操作方法
const addHistory = (url) => {
  const newRecord = {
    url,
    time: new Date().getTime(),
  };

  // 去重并保持最新在前
  historyList.value = [
    newRecord,
    ...historyList.value.filter((item) => item.url !== url),
  ].slice(0, MAX_HISTORY);

  // 保存到本地存储
  localStorage.setItem("videoTestHistory", JSON.stringify(historyList.value));
};

const loadHistory = () => {
  const history = localStorage.getItem("videoTestHistory");
  if (history) {
    historyList.value = JSON.parse(history);
  }
};

const applyHistory = (url) => {
  videoUrl.value = url;
  testVideo();
};

const formatTime = (timestamp) => {
  return new Date(timestamp).toLocaleTimeString();
};

const handlePlaceholderError = (error) => {
  if (playerRef.value && typeof playerRef.value.dispose === 'function') {
    playerRef.value.dispose();
  }
  if (!currentUrl.value) {
    showPlayer.value = false;
  } else {
    errorMessage.value = `播放失败: ${error.message}`;
    showPlayer.value = false;
  }
};

// 新增清除方法
const clearInput = () => {
  videoUrl.value = ''
  currentUrl.value = ''
  showPlayer.value = false
  errorMessage.value = ''
}

const handlePlayerReady = (player) => {
  playerRef.value = player;
  try {
    if (player && typeof player.play === 'function') {
      player.play();
    } else {
      console.log('播放器已自动启动');
    }
  } catch (err) {
    if (err.message.includes('play')) {
      // 忽略浏览器自动播放策略的警告
    } else {
      console.warn('播放异常:', err.message);
    }
    errorMessage.value = '点击播放按钮开始播放';
  }
}

onMounted(() => {
  loadHistory();
  utools.setExpendHeight(500);
  utools.onPluginReady(() => {
    console.log("插件准备就绪");
  });
});
</script>

<template>
  <div class="container">
    <div class="input-group">
      <input v-model="videoUrl" type="text" placeholder="输入视频链接（支持mp4/m3u8/直播流）" @keyup.enter="testVideo" />
      <button @click="testVideo" :disabled="loading">
        {{ loading ? "检测中..." : "立即检测" }}
      </button>
      <button @click="clearInput" class="clear-btn">
        清除
      </button>
    </div>

    <div class="player-container">
      <video-player
        :key="currentUrl"
        v-if="showPlayer || !currentUrl"
        :src="currentUrl || ''"
        :muted="true"
        @error="handlePlaceholderError"
        @ready="handlePlayerReady"
      />
      <div v-if="!currentUrl" class="placeholder-tip">
        <span>👆 请输入视频链接后点击「立即检测」</span>
      </div>
    </div>

    <div v-if="errorMessage" class="error-message">
      {{ errorMessage }}
    </div>

    <!-- 新增历史记录区域 -->
    <div class="history-section" v-if="historyList.length > 0">
      <h3>检测历史</h3>
      <ul>
        <li v-for="(item, index) in historyList" :key="index" @click="applyHistory(item.url)">
          <span class="time">{{ formatTime(item.time) }}</span>
          <span class="url">{{ item.url }}</span>
        </li>
      </ul>
    </div>

  </div>
</template>

<style>
:root {
  --primary-color: #6a1b9a;
  --secondary-color: #9c27b0;
  --background: #f3e5f5;
}

.container {
  padding: 15px;
  background: var(--background);
  height: 100%;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.input-group {
  display: flex;
  gap: 10px;
  margin-bottom: 10px;
}

input {
  flex: 1;
  padding: 12px;
  border: 2px solid var(--primary-color);
  border-radius: 8px;
  font-size: 14px;
}

button {
  padding: 12px 24px;
  background: var(--primary-color);
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  transition: background 0.3s;
}

button:hover {
  background: var(--secondary-color);
}

button:disabled {
  background: #b39ddb;
  cursor: not-allowed;
}

.player-container {
  margin-top: 0px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  flex: 1;
  min-height: 300px;
  width: calc(100%);
}

.error-message {
  color: #d32f2f;
  margin-top: 15px;
  padding: 10px;
  background: #ffebee;
  border-radius: 4px;
}

/* 新增历史记录样式 */
.history-section {
  margin-top: 30px;
  border-top: 2px solid var(--primary-color);
  padding-top: 20px;
  margin-left: -15px;
  margin-right: -15px;
  padding-left: 15px;
  padding-right: 15px;
  flex-shrink: 0;
  max-height: 200px;
  overflow: visible;
}

.history-section h3 {
  color: var(--primary-color);
  margin-bottom: 15px;
  font-size: 16px;
}

.history-section ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

.history-section li {
  padding: 10px;
  margin: 8px 0;
  background: white;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s;
  display: flex;
  gap: 15px;
  align-items: center;
}

.history-section li:hover {
  transform: translateX(5px);
  box-shadow: 0 2px 8px rgba(106, 27, 154, 0.2);
}

.history-section .time {
  color: #9c27b0;
  font-size: 12px;
  flex-shrink: 0;
}

.history-section .url {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  color: #4a148c;
}

/* 添加全局滚动条样式 */
::-webkit-scrollbar {
  width: 6px;
  background: #f3e5f5;
}

::-webkit-scrollbar-thumb {
  background: var(--primary-color);
  border-radius: 3px;
}

/* 新增占位提示样式 */
.placeholder-tip {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: var(--primary-color);
  font-size: 16px;
  text-align: center;
  z-index: 1;
  background: rgba(255, 255, 255, 0.9);
  padding: 15px 25px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.placeholder-tip span {
  display: inline-block;
  animation: float 2s ease-in-out infinite;
}

@keyframes float {

  0%,
  100% {
    transform: translateY(0);
  }

  50% {
    transform: translateY(-5px);
  }
}

/* 新增清除按钮样式 */
.clear-btn {
  background: #e45e5e !important;
  color: #ffffff !important;
}

.clear-btn:hover {
  background: #f73d3d !important;
}

.player-notice {
  position: absolute;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  background: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 8px 16px;
  border-radius: 4px;
  font-size: 12px;
}

.video-js {
  width: 100%;
}
</style>
